package com.diyunapp.xilinapp.myindent;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.bean.AddEvaBean;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.selfdefine.StatusBarFragmentActivity;
import com.diyunapp.xilinapp.utils.AbDateUtil;
import com.diyunapp.xilinapp.utils.BitmapUtil;
import com.diyunapp.xilinapp.utils.ScrollListViewDisplay;
import com.diyunapp.xilinapp.utils.UploadUtilEva;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.squareup.picasso.Picasso;
import com.yuyh.library.imgsel.ImageLoader;
import com.yuyh.library.imgsel.ImgSelActivity;
import com.yuyh.library.imgsel.ImgSelConfig;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AddEvaluationActivity extends StatusBarFragmentActivity implements View.OnClickListener , UploadUtilEva.OnUploadProcessListener{

    public String re_id;
    public String order_id;
    public String gd_pi;
    @Bind(R.id.go_back1)
    ImageView goBack1;
    @Bind(R.id.evaluation_recylerView)
    ListView evaluationRecylerView;
    @Bind(R.id.login_tv)
    TextView loginTv;
    private List<AddEvaBean.DataBean> evaInfo;
    private AddEvaAdapter addEvaAdapter;
    private String OrderId;
    private LayoutInflater inflater;
    private String src1 = null;
    private String src2 = null;
    private String src3 = null;
    private String src4 = null;
    private String src5 = null;
    private  List<String> pathList=null;
    private int pzState=99999000;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_evaluation);
        ButterKnife.bind(this);
        OrderId = getIntent().getExtras().getString("OrderId");
        View headView;
        headView = findViewById(R.id.addeva_menubar_inc);
        super.MenuWidget(headView);
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        evaInfo = new ArrayList<>();
        addEvaAdapter=new AddEvaAdapter(evaInfo,this);

        evaluationRecylerView.setAdapter(addEvaAdapter);
        initView();
//        initOldEvaluation();
//        toast(order_id);
    }

    private void initView() {
        String url = "" + MainActivity.url + "act=goods&op=zjplinfo&order_id="+OrderId+"";
        Log.i("xiaogaladebug", "url++" + url);
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
//                        bidFreshLv.onRefreshComplete();

                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
//                        Logger.e("=================================="+resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.getInt("code");
                            if (result == 200) {
                                JSONArray order_goods = resultObject.optJSONArray("data");
                                for (int i = 0; i < order_goods.length(); i++) {
                                    JSONObject recordObject = order_goods.optJSONObject(i);
                                    String geval_content = recordObject.optString("geval_content");
                                    long geval_addtime = recordObject.optLong("geval_addtime");
                                    String geval_ordergoodsid = recordObject.optString("geval_ordergoodsid");
                                    String image=recordObject.optString("image");
                                    evaInfo.add(new AddEvaBean.DataBean(geval_addtime,
                                            geval_content, geval_ordergoodsid,image));
                                }
//                                receiveAdapter.setList(info);
                                addEvaAdapter.notifyDataSetChanged();
                                ScrollListViewDisplay.setListViewHeightBasedOnChildren(evaluationRecylerView);
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            toast("查询失败");
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onFailure(HttpException error, String msg) {
                        toast("请求失败");
                    }
                });
    }

    private void postPic(String id,List<String> list) {
        String uploadURL = MainActivity.url+"act=goods&op=zjevaupload_pic";
        Log.i("zhangxiaoxidebug","-------"+uploadURL);
        UploadUtilEva uploadUtil = UploadUtilEva.getInstance();
        uploadUtil.setOnUploadProcessListener(this); //设置监听器监听上传状态
        Map<String, String> params = new HashMap<String, String>();
        params.put("member_id", MainActivity.myLogin.getMemberid());
        params.put("goods_id",id );

        if(pzState!=99999000) {
            if(list.size()==5){
//                toasts("正在上传凭证5，请稍后");
                src1 = list.get(0);
                src2 = list.get(1);
                src3 = list.get(2);
                src4 = list.get(3);
                src5 = list.get(4);
                uploadUtil.uploadFile( src1,src2,src3,src4,src5,uploadURL,params);
            }else if (list.size()==4){
//                toasts("正在上传凭证4，请稍后");
                src1 = list.get(0);
                src2 = list.get(1);
                src3 = list.get(2);
                src4 = list.get(3);
                uploadUtil.uploadFile( src1,src2,src3,src4,uploadURL,params);}
            else
            if (list.size()==3){
//                toasts("正在上传凭证3，请稍后");
                String path1 = list.get(0);
                String path2 = list.get(1);
                String path3 = list.get(2);
                uploadUtil.uploadFile( path1,path2,path3,uploadURL,params);
            }else if (list.size()==2){

//                toasts("正在上传凭证2，请稍后");
                String path1 = list.get(0);
                String path2 = list.get(1);
                uploadUtil.uploadFile( path1,path2,uploadURL,params);
            }else if (list.size()==1){
//                toasts("正在上传凭证1，请稍后");
                String path1 = list.get(0);
                uploadUtil.uploadFile( path1,uploadURL,params);
            }
        }else{
            Log.i("zhangxiaoxi","无照片上传"+id);
        }
    }
    private void addEvaluation() {
//        String url = "" + MainActivity.url + "ct=goods&op=add_comments";
        String url = MainActivity.url + "act=goods&op=add_comments";
        RequestParams params = new RequestParams();
        params.addBodyParameter("order_id", OrderId);
        String message = getMessage();
        params.addBodyParameter("evaluate_comment",message);
        params.addBodyParameter("member_id",MainActivity.myLogin.getMemberid());
        Log.i("zhangxiaoxidebug", "resultinfo=" + url);
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,params,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");

                            if (result == 200) {
                                String data = resultObject.optString("data");

                                if(pzState!=99999000){
                                    for (int i = 0; i < evaInfo.size(); i++) {
                                        int ps=evaInfo.get(i).getPosotion();
                                        String id=evaInfo.get(i).getGeval_ordergoodsid();
                                        List<String> list=evaInfo.get(i).getPathList();
                                        if(ps==pzState){
                                            postPic(id,list);
                                        }else{
                                            Log.i("zhangxiaoxidebug","无图片");
                                        }
                                    }
                                }else if(pzState==99999000){
                                    toast(data);
                                    setResult(1);
                                    finish();
                                }

                            } else {
                                String data = resultObject.optString("data");
                                toast(data);
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            toast("查询失败");
                            e.printStackTrace();

                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {

                        toast("请求失败");

                    }
                });
    }



    @OnClick({R.id.go_back1, R.id.login_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.go_back1:
                finish();
                break;
            case R.id.login_tv:
                addEvaluation();
//                doAdd();
                break;
        }
    }

    private String getMessage() {

        StringBuffer sayBuffer = new StringBuffer();
        for (int i = 0; i < evaInfo.size(); i++) {
            String sayInfo = String.valueOf(evaInfo.get(i).getEva_content());
//            String evainfo=toUtf8String(sayInfo);
            String goodId = evaInfo.get(i).getGeval_ordergoodsid();

            if (!sayInfo.isEmpty()) {
                sayBuffer.append(goodId + "|" + sayInfo + ",");
            }
        }
        if (sayBuffer.length() > 0) {
            sayBuffer.deleteCharAt(sayBuffer.length() - 1);
        }
        Log.i("zhangxiaoxidebug", "sayBuffer = " + sayBuffer.toString());
        return sayBuffer.toString();
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 图片选择结果回调
        // 图片选择结果回调
        for (int i = 0; i < evaInfo.size(); i++) {
//                String scoreInfo = String.valueOf(evaInfo.get(i).getEva_scorel());

            int posotion = evaInfo.get(i).getPosotion();

            if (requestCode == posotion && resultCode == RESULT_OK && data != null) {
                Log.i("xiaogaladebug","++"+posotion);
                pathList = data.getStringArrayListExtra(ImgSelActivity.INTENT_RESULT);
                if(pathList.size()!=0){
                    pzState=posotion;
                }

                Log.i("zhangxiaoxidebug","11111+"+pathList.size());
                addEvaAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onUploadDone(int responseCode, String message) {
        Message myMes = Message.obtain();
        myMes.arg1 = responseCode;
        myMes.obj = message;
        myPicupHandle.sendMessage(myMes);

    }

    @Override
    public void onUploadProcess(int uploadSize) {
        Message myMes = Message.obtain();
        myMes.arg1 = 10;
        myMes.arg2 = uploadSize;
        myPicupHandle.sendMessage(myMes);
    }
    private Handler myPicupHandle = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.arg1) {
                case UploadUtilEva.UPLOAD_SUCCESS_CODE:
                    toast("提交成功");
                    setResult(1);
                    finish();
                    break;
                case UploadUtilEva.UPLOAD_SERVER_ERROR_CODE:
                    String error = msg.obj.toString();
                    toast(error);
                    break;
                case 10:
                    toasts("正在提交，请稍后...");
                    Log.i("zhangxiaoxidebug","正在上传");
                    break;
                default:
                    break;
            }
        }

    };
    @Override
    public void initUpload(int fileSize) {

    }

    class AddEvaAdapter extends BaseAdapter implements View.OnClickListener {
        private List<AddEvaBean.DataBean> list;
        private Context context;

        public AddEvaAdapter(List<AddEvaBean.DataBean> list, Context context) {

            this.list = list;
            this.context = context;
        }

        @Override
        public int getCount() {
            return null == list ? 0 : list.size();
        }

        @Override
        public Object getItem(int position) {
            return null == list ? null : list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.item_add_eva, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final ViewHolder viewHolder = holder;
            final AddEvaBean.DataBean bean = list.get(position);
//            final ReceiveBean.OrderGoodsBean currentdata = bean.get(position);
            viewHolder.oldEvaluateContent.setText(bean.getGeval_content());
            viewHolder.evaluationTime.setText(AbDateUtil.getStringByFormat(bean.getGeval_addtime()*1000,"yyyy-MM-dd"));
            String image =bean.getImage();
            Picasso.with(context)
                    .load(image)
                    .resize(200, 200)
                    .centerCrop()
                    .placeholder(R.drawable.list_default)
                    .error(R.drawable.list_default)
                    .into(viewHolder.goodsImage);
            viewHolder.addEvaluation.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    bean.setEva_content(s.toString());
                }
                @Override
                public void afterTextChanged(Editable s) {
                }
            });
            viewHolder.shangchuan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ImgSelActivity.startActivity((Activity) context, config, position);
                    bean.setPosotion(position);
                }
            });

            if (position == pzState) {
                bean.setPathList(pathList);
//                if(pzState==1){
                src1 = null;
                src2 = null;
                src3 = null;
                if (pathList.size() == 1) {
                    src1 = pathList.get(0);
                    viewHolder.shangchuan.setVisibility(View.VISIBLE);
                    Bitmap bitmap = BitmapUtil.createThumbnail(src1,100, 100);
                    viewHolder.shangchuan.setImageBitmap(bitmap);
                }else if (pathList.size() == 2) {
                    src1 = pathList.get(0);
                    src2 = pathList.get(1);
                    viewHolder.shangchuan.setVisibility(View.VISIBLE);
                    viewHolder.shangchuan1.setVisibility(View.VISIBLE);
                    Bitmap bitmap = BitmapUtil.createThumbnail(src1,100, 100);
                    viewHolder.shangchuan.setImageBitmap(bitmap);
                    Bitmap bitmap1 = BitmapUtil.createThumbnail(src2,  100, 100);
                    viewHolder.shangchuan1.setImageBitmap(bitmap1);

                }else if (pathList.size() == 3) {
                    src1 = pathList.get(0);
                    src2 = pathList.get(1);
                    src3 = pathList.get(2);
                    viewHolder.shangchuan.setVisibility(View.VISIBLE);
                    viewHolder.shangchuan1.setVisibility(View.VISIBLE);
                    viewHolder.shangchuan2.setVisibility(View.VISIBLE);

                    Bitmap bitmap = BitmapUtil.createThumbnail(src1, 100, 100);
                    viewHolder.shangchuan.setImageBitmap(bitmap);

                    Bitmap bitmap1 = BitmapUtil.createThumbnail(src2,  100, 100);
                    viewHolder.shangchuan1.setImageBitmap(bitmap1);

                    Bitmap bitmap2 = BitmapUtil.createThumbnail(src3, 100, 100);
                    viewHolder.shangchuan2.setImageBitmap(bitmap2);
                }else if (pathList.size() == 4) {
                    src1 = pathList.get(0);
                    src2 = pathList.get(1);
                    src3 = pathList.get(2);
                    src4 = pathList.get(3);
                    viewHolder.shangchuan.setVisibility(View.VISIBLE);
                    viewHolder.shangchuan1.setVisibility(View.VISIBLE);
                    viewHolder.shangchuan2.setVisibility(View.VISIBLE);
                    viewHolder.shangchuan3.setVisibility(View.VISIBLE);
                    Bitmap bitmap = BitmapUtil.createThumbnail(src1, 100, 100);
                    viewHolder.shangchuan.setImageBitmap(bitmap);
                    Bitmap bitmap1 = BitmapUtil.createThumbnail(src2,  100, 100);
                    viewHolder.shangchuan1.setImageBitmap(bitmap1);
                    Bitmap bitmap2 = BitmapUtil.createThumbnail(src3, 100, 100);
                    viewHolder.shangchuan2.setImageBitmap(bitmap2);
                    Bitmap bitmap3 = BitmapUtil.createThumbnail(src4, 100, 100);
                    viewHolder.shangchuan3.setImageBitmap(bitmap3);
                }
                else if (pathList.size() == 5) {
                    src1 = pathList.get(0);
                    src2 = pathList.get(1);
                    src3 = pathList.get(2);
                    src4 = pathList.get(3);
                    src5 = pathList.get(4);
                    viewHolder.shangchuan.setVisibility(View.VISIBLE);
                    viewHolder.shangchuan1.setVisibility(View.VISIBLE);
                    viewHolder.shangchuan2.setVisibility(View.VISIBLE);
                    viewHolder.shangchuan3.setVisibility(View.VISIBLE);
                    viewHolder.shangchuan4.setVisibility(View.VISIBLE);
                    Bitmap bitmap = BitmapUtil.createThumbnail(src1, 100, 100);
                    viewHolder.shangchuan.setImageBitmap(bitmap);

                    Bitmap bitmap1 = BitmapUtil.createThumbnail(src2,  100, 100);
                    viewHolder.shangchuan1.setImageBitmap(bitmap1);

                    Bitmap bitmap2 = BitmapUtil.createThumbnail(src3, 100, 100);
                    viewHolder.shangchuan2.setImageBitmap(bitmap2);
                    Bitmap bitmap3 = BitmapUtil.createThumbnail(src4, 100, 100);
                    viewHolder.shangchuan3.setImageBitmap(bitmap3);
                    Bitmap bitmap4 = BitmapUtil.createThumbnail(src5, 100, 100);
                    viewHolder.shangchuan4.setImageBitmap(bitmap4);
                }
//                }
            }

            return convertView;
        }

        @Override
        public void onClick(View v) {

        }
        private ImageLoader loader = new ImageLoader() {
            @Override
            public void displayImage(Context context, String path, ImageView imageView) {
                // TODO 在这边可以自定义图片加载库来加载 ImageView，例如 Glide、Picasso、ImageLoader 等
                Glide.with(context).load(path).into(imageView);
            }
        };
        ImgSelConfig config = new ImgSelConfig.Builder(loader)
                // 是否多选
                .multiSelect(true)
                .btnTextColor(Color.WHITE)
                // 使用沉浸式状态栏
                .statusBarColor(Color.parseColor("#eb534a"))
                // 返回图标 ResId
                .backResId(R.drawable.goback)
                // 标题
                .title("图片")
                // 标题文字颜色
                .titleColor(Color.WHITE)
                // TitleBar 背景色
                .titleBgColor(Color.parseColor("#eb534a"))
                .needCamera(true)
                // 最大选择图片数量
                .maxNum(5)
                .build();


         class ViewHolder {
            @Bind(R.id.goods_image)
            ImageView goodsImage;
            @Bind(R.id.old_evaluate_content)
            TextView oldEvaluateContent;
            @Bind(R.id.evaluation_time)
            TextView evaluationTime;
            @Bind(R.id.add_evaluation)
            EditText addEvaluation;
            @Bind(R.id.shangchuan)
            ImageView shangchuan;
             @Bind(R.id.shangchuan1)
             ImageView shangchuan1;
             @Bind(R.id.shangchuan2)
             ImageView shangchuan2;
             @Bind(R.id.shangchuan3)
             ImageView shangchuan3;
             @Bind(R.id.shangchuan4)
             ImageView shangchuan4;
            ViewHolder(View view) {
                ButterKnife.bind(this, view);
            }
        }
    }

    public void toasts(String msg){
        Toast.makeText(this,msg,Toast.LENGTH_LONG).show();
    }
}
